<template>
  <a-form
    :form="form"
    :label-col="{ span: 8 }"
    :label-align="'left'"
    @submit="handleSubmit"
  >
    <a-form-item label="服务器" has-feedback>
      <a-input
        v-decorator="[
          'server',
          { rules: [{ required: true, message: '请填写服务器!' }] },
        ]"
        class="col-container"
        size="small"
        style="width: 480px;"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item label="端口" has-feedback>
      <a-input
        v-decorator="[
          'port',
          { rules: [{ required: true, message: '请填写端口!' }] },
        ]"
        class="col-container"
        size="small"
        style="width: 480px;"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item
      v-if="selectedDatabaseType === databaseMapping.oracle"
      label="服务名或SID"
      style="height: 75px;"
      has-feedback
      class="server-sid-item"
    >
      <a-radio-group
        v-decorator="[
          'connectType',
          {
            rules: [{ required: true, message: '服务名或SID!' }],
            initialValue: 'servicename',
          },
        ]"
        style="margin-left: 6px;"
        @change="changeDatabaseConfig"
      >
        <a-radio class="radio-container" value="servicename">服务名</a-radio>
        <a-radio class="radio-container" value="sid">SID </a-radio>
      </a-radio-group>
      <br />
      <a-input
        v-decorator="[
          'connectValue',
          { rules: [{ required: true, message: '请填写服务名或SID!' }] },
        ]"
        class="col-container"
        size="small"
        style="width: 480px;"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item label="数据库账号" has-feedback>
      <a-input
        v-decorator="[
          'user',
          { rules: [{ required: true, message: '请填写用户名!' }] },
        ]"
        class="col-container"
        size="small"
        style="width: 480px;"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item label="数据库密码" has-feedback>
      <a-input
        v-decorator="[
          'password',
          { rules: [{ required: true, message: '请填写密码!' }] },
        ]"
        class="col-container col-container-oracle"
        size="small"
        type="password"
        style="width: 480px;"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item>
      <div class="col-container testing">
        <a-button
          class="testing-database-button"
          style="height: 28px; width: 81px;"
          html-type="submit"
        >
          连接测试
        </a-button>
        <span v-if="testState !== 'BEFORE_TEST'" class="testing-status">
          <a-spin v-if="testState === 'TESTING'" />
          <span
            v-else-if="testState === 'TEST_SUCCEED'"
            style="color: #78c06e;"
          >
            <a-icon
              type="check-circle"
              style="color: #78c06e;"
              theme="filled"
            />
            连接成功
          </span>
          <span v-else>
            <a-icon type="close-circle" theme="filled" />
            连接失败
            <a-button type="link" html-type="submit">重新测试</a-button>
          </span>
        </span>
      </div>
    </a-form-item>
    <a-form-item v-if="testState === 'TEST_SUCCEED'" label="数据库（D）">
      <a-select
        v-decorator="[
          'databaseName',
          { rules: [{ required: true, message: '请选择数据库!' }] },
        ]"
        placeholder="请选择"
        class="col-container"
        style="width: 480px;"
        size="small"
        @change="changeSelectedDatabase"
      >
        <a-select-option
          v-for="option in databaseOptions"
          :key="option"
          :value="option"
        >
          {{ option }}
        </a-select-option>
      </a-select>
    </a-form-item>
  </a-form>
  <!-- </a-modal> -->
</template>

<script lang="ts">
/**
 * modal of testing database
 * @author Huihua Lu
 */
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import DataStore, { DatabaseTestState } from '@/store/modules/data'

@Component
export default class DatabaseModal extends Vue {
  @Prop() selectedDatabaseType!: string

  private form: any

  private selectedDatabase: string = ''

  private databaseMapping = {
    mysql: 'MySql',
    oracle: 'oracle',
  }

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'database_form' })
  }

  public get testState() {
    return DataStore.testState
  }

  public get databaseOptions() {
    return DataStore.databaseOptions
  }

  public handleSubmit(event: Event) {
    event.preventDefault()
    this.form.validateFields(async (error: Error, values: any) => {
      if (!error) {
        const { connectType, connectValue } = values
        let passData: any = {
          databaseType: this.selectedDatabaseType,
          server: values.server,
          port: values.port,
          user: values.user,
          password: values.password,
        }
        if (this.selectedDatabaseType === this.databaseMapping.oracle) {
          passData = {
            ...passData,
            connectType,
            connectValue,
          }
        }
        DataStore.setDatabaseConfig(passData)
        await DataStore.testConnection(passData)
      } else {
        console.log('error:', error)
      }
    })
  }

  // 编辑数据库连接信息
  public changeDatabaseConfig() {
    DataStore.setTestState(DatabaseTestState.BEFORE_TEST)
    this.$emit('set-is-database-chosen', false)
  }

  public changeSelectedDatabase(value: string) {
    this.selectedDatabase = value
  }

  @Watch('selectedDatabase')
  public importDatabase() {
    // event.preventDefault()
    if (this.testState !== DatabaseTestState.TEST_SUCCEED) {
      // 还未通过测试时，点击确定会提示进行测试
      this.$message.error('请先进行数据库连接测试!')
      return
    }
    this.form.validateFields(async (error: Error) => {
      // 通过测试后，点击确定会提交相应数据，并获取所有表
      if (!error) {
        const passData = {
          ...DataStore.databaseConfig,
          databaseName: this.selectedDatabase,
        }
        DataStore.setDatabaseConfig(passData)
        await DataStore.queryDatabaseTables(passData)
        this.$emit('set-is-database-chosen', true)
        DataStore.setSelectedTables([])
      } else {
        console.log('error:', error)
      }
    })
  }
}
</script>
<style lang="less" scoped>
/* 表格行的样式 */
.ant-row {
  margin: 0;
}

.col-container {
  border-radius: 4px;
  margin-left: 8px;

  &.testing {
    padding-left: 100px;
    padding-top: 2px;

    /deep/ .testing-database-button {
      padding: auto 12px;
      padding-left: 12px;
    }

    .testing-status {
      margin-left: 20px;
    }
  }
}
</style>
<style lang="less" scoped>
.ant-form-item {
  display: flex;
  height: 40px;
  margin-bottom: 6px;
  width: 100%;
}

/deep/ .ant-col-8 {
  width: 100px;
}

/deep/ .col-container-oracle {
  .ant-radio-group {
    margin-left: 8px;
  }

  input {
    left: 0;
    position: absolute;
    top: 28px;
  }
}

/deep/ .ant-form-item-control-wrapper {
  width: 100%;

  .ant-form-item-children-icon {
    left: 491px;
  }

  .ant-form-explain {
    left: 522px;
    position: absolute;
    top: 10px;
  }
}

// 服务器与SID样式
.server-sid-item {
  /deep/ .ant-form-item-children-icon {
    top: 43px;
  }

  /deep/ .ant-form-explain {
    top: 43px;
  }
}
</style>
